package top.withwings.bonus.bonus.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.withwings.bonus.bonus.pojo.OnSaleForm;
import top.withwings.bonus.bonus.pojo.bonus.rule.OnSaleBonusRule;
import top.withwings.bonus.bonus.repo.BonusRuleRepo;
import top.withwings.bonus.bonus.repo.OnSaleFormRepo;
import top.withwings.bonus.common.pojo.PageParam;
import top.withwings.bonus.common.pojo.PagedData;

import java.util.Date;
import java.util.List;

@Service
public class OnSaleFormService {

    @Autowired
    private OnSaleFormRepo onSaleFormRepo;

    @Autowired
    private BonusRuleRepo bonusRuleRepo;

    public int create(OnSaleForm form) {
        checkPeriodLegal(form);
        checkPeriodOverlapForCreate(form);
        return onSaleFormRepo.create(form);
    }


    public void delete(int formId) {
        onSaleFormRepo.delete(formId);
    }

    public void update(OnSaleForm form) {
        checkPeriodLegal(form);
        checkPeriodOverlapUpdate(form);
        onSaleFormRepo.update(form);

    }



    public PagedData<OnSaleForm> findByGood(PageParam pageParam,Integer goodId) {
        return this.findByGoodAndTime(pageParam, goodId, null);
    }


    @Transactional
    public PagedData<OnSaleForm> findByGoodAndTime(PageParam pageParam ,Integer goodId, Date referDate) {

        int total = onSaleFormRepo.count(goodId, referDate);
        if (total == 0) {
            return PagedData.emptyPage();
        }
        List<OnSaleForm> forms = onSaleFormRepo.search(pageParam ,goodId, referDate);
        for (OnSaleForm onSaleForm : forms) {
            onSaleForm.setRule((OnSaleBonusRule) bonusRuleRepo.findById(onSaleForm.getRule().getId()));
        }
        return PagedData.create(forms, total);
    }


    private void checkPeriodOverlapForCreate(OnSaleForm form) {

        //TODO
    }

    private void checkPeriodOverlapUpdate(OnSaleForm form) {
        //TODO
    }



    private void checkPeriodLegal(OnSaleForm form) {

        if(form.getStart().before(form.getEnd())){
            //OK
        }else {
            throw  new IllegalArgumentException("开始时间必须小于结束时间");
        }

    }

}















